package com.lm.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;

import com.lm.util.AliYunImage;
import com.lm.util.ResultUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.IOException;
import java.util.Date;

@RestController
@RequestMapping("/imageCtl")
@CrossOrigin(origins = "*")
@Api(tags = "图片上传")
public class UploadController {


    @Autowired //阿里云图片上传
    private AliYunImage aliYunImage;



    //    接收前端图片
    /**
     * @description:
     * @param: file
     * @return: com.lm.util.ResultUtil<java.lang.String>
     * @author 32477
     * @date: 2025/9/21 22:08
     */
    @ApiOperation(value = "上传图片", notes = "上传图片", httpMethod = "POST")
    @PostMapping("/uploadImg")
    public ResultUtil<String> uploadImg(@RequestParam("file") CommonsMultipartFile file) throws IOException {
        System.out.println(file.getInputStream());//获取图片流
        System.out.println(file.getOriginalFilename());
//        保存图片到指定位置 自己本地服务器
//        File file1 = new File("D:\\JavaTool\\apache-tomcat-9.0.43\\webapps\\ROOT"+file.getOriginalFilename());
//        file.transferTo(file1);//保存图片到指定位置
        String newFileName = new Date().getTime()+file.getOriginalFilename();
        //连接oss
        OSS ossClient = new OSSClientBuilder().build("https://"+aliYunImage.getEndpoint(),
                aliYunImage.getAccessKeyId(), aliYunImage.getAccessKeySecret());
        //长传文件
        ossClient.putObject(aliYunImage.getBucketName(), newFileName,
                file.getInputStream());
        //拼接文件在oss中访问地址
        String url = "https://"+aliYunImage.getBucketName()+"."+aliYunImage.getEndpoint()+"/"+newFileName;

        return new ResultUtil<>(200, "上传成功", url);
    }
    //删除新闻图片
    /**
     * @description:
     * @param: imgUrl
     * @return: com.lm.util.ResultUtil<java.lang.String>
     * @author 32477
     * @date: 2025/9/21 22:09
     */
    @ApiOperation(value = "删除图片", notes = "删除图片", httpMethod = "DELETE")
    @DeleteMapping("/deleteImg")
    public ResultUtil<String> deleteImg(@RequestParam("imgUrl") String imgUrl) {
        // 提取并清理文件名：去除首尾引号
        String fileName = imgUrl.substring(imgUrl.lastIndexOf("/") + 1)
                .replaceAll("^[\"']+|[\"']+$", "");
        System.out.println("删除文件：" + fileName);
        // 连接 OSS 并删除
        OSS ossClient = new OSSClientBuilder().build(
                "https://" + aliYunImage.getEndpoint(),
                aliYunImage.getAccessKeyId(),
                aliYunImage.getAccessKeySecret()
        );
        ossClient.deleteObject(aliYunImage.getBucketName(), fileName);
        ossClient.shutdown(); // 记得关闭客户端！原代码漏了，会导致连接泄漏

        return new ResultUtil<>(200, "删除成功", null);
    }

}
